package com.ihd.ihardware.view.tzc.me.view;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.ihd.ihardware.R;
import com.ihd.ihardware.common.AppConstans;
import com.ihd.ihardware.databinding.ActivityPerInfoBinding;
import com.ihd.ihardware.pojo.EmptyRes;
import com.ihd.ihardware.pojo.FileRes;
import com.ihd.ihardware.pojo.OPValue;
import com.ihd.ihardware.pojo.UserInfoRes;
import com.ihd.ihardware.view.tzc.main.view.BalanceActivity;
import com.ihd.ihardware.view.tzc.me.viewmodel.TargetViewModel;

import org.jaaksi.pickerview.dataset.OptionDataSet;
import org.jaaksi.pickerview.picker.OptionPicker;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.wowjoy.commonlibrary.adapter.DialogListAdapter;
import cn.wowjoy.commonlibrary.base.BaseActivity;
import cn.wowjoy.commonlibrary.base.BaseConsumer;
import cn.wowjoy.commonlibrary.utils.DialogUtils;
import cn.wowjoy.commonlibrary.utils.ImageUtils;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;
import cn.wowjoy.commonlibrary.widget.CustomDatePicker;
import cn.wowjoy.commonlibrary.widget.MDialog;

public class PerInfoActivity extends BaseActivity<ActivityPerInfoBinding, TargetViewModel> {
    public static final int PHOTO_PICKED_WITH_PATH = 3022;
    public static final int CAMERA_WITH_DATA = 3023;
    private MDialog mBottomDG;
    private CustomDatePicker customDatePicker;
    private String avatar;
    private int sex = 2;
    private OptionPicker mHPicker;
    private List<OPValue> height = new ArrayList<>();
    private OptionPicker mWPicker;
    private List<OPValue> weight = new ArrayList<>();
    private UserInfoRes.DataBean uInfo;

    @Override
    protected void init(Bundle savedInstanceState) {
        mImmersionBar.statusBarDarkFont(false).init();

        uInfo = (UserInfoRes.DataBean) getIntent().getSerializableExtra("userinfo");

        for (float i = 30.0f; i < 180.0f; i += 0.5f) {
            weight.add(new OPValue(new BigDecimal(i).setScale(1, 4).toString()));
        }
        for (int i = 80; i < 251; i++) {
            height.add(new OPValue(String.valueOf(i)));
        }

        mWPicker = new OptionPicker.Builder(this, 1, new OptionPicker.OnOptionSelectListener() {
            @Override
            public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {
                binding.weightTV.setText(weight.get(selectedPosition[0]).getValue());
                binding.weightTV.setTextColor(getResources().getColor(R.color.C_333333));
            }
        }).create();

        mHPicker = new OptionPicker.Builder(this, 1, new OptionPicker.OnOptionSelectListener() {
            @Override
            public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {
                binding.heightTV.setText(height.get(selectedPosition[0]).getValue());
                binding.heightTV.setTextColor(getResources().getColor(R.color.C_333333));
            }
        }).create();

        if (uInfo != null) {
            Glide.with(getApplicationContext())
                    .load(Uri.parse(uInfo.getAvatar()))
                    .apply(RequestOptions.circleCropTransform())
                    .into(binding.header);
            avatar = uInfo.getAvatar();
            binding.nickTV.setText(uInfo.getNickName());
            if (uInfo.getSex() == 1) {
                binding.fTV.setTextColor(getResources().getColor(R.color.C_898B90));
                binding.fTV.setBackgroundResource(R.drawable.corners_left_e8e9f0);
                binding.mTV.setTextColor(getResources().getColor(R.color.C_FFFFFF));
                binding.mTV.setBackgroundResource(R.drawable.corners_right_46a5f9);
                sex = 1;
            } else {
                binding.fTV.setTextColor(getResources().getColor(R.color.C_FFFFFF));
                binding.fTV.setBackgroundResource(R.drawable.corners_left_9065f9);
                binding.mTV.setTextColor(getResources().getColor(R.color.C_898B90));
                binding.mTV.setBackgroundResource(R.drawable.corners_right_e8e9f0);
                sex = 2;
            }
            binding.birthTV.setText(uInfo.getBirthDay());
            binding.heightTV.setText(uInfo.getHeight());
            binding.weightTV.setText(uInfo.getWeight());
            mWPicker.setDataWithValues(weight, TextUtils.isEmpty(uInfo.getWeight()) ? "50.0" : uInfo.getWeight());
            mHPicker.setDataWithValues(height, (TextUtils.isEmpty(uInfo.getHeight()) || "0".equals(uInfo.getHeight())) ? "165" : uInfo.getHeight());
        } else {
            mWPicker.setDataWithValues(weight, "50.0");
            mHPicker.setDataWithValues(height, "165");
        }

        binding.headRL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomDG = DialogUtils.BottomListDialog(PerInfoActivity.this, Arrays.asList("拍照", "从相册中选择"), new DialogListAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, String data) {
                        mBottomDG.cancel();
                        if (data.equals("拍照")) {
                            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri imguri = Uri.fromFile(new File(AppConstans.BASE_PATH + AppConstans.HEAD_PATH));
                            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imguri);
                            startActivityForResult(openCameraIntent, CAMERA_WITH_DATA);
                        } else {
                            Intent intent = new Intent(Intent.ACTION_PICK);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, PHOTO_PICKED_WITH_PATH);
                        }
                    }
                });
            }
        });

        binding.nickTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomDG = DialogUtils.inputDialog(PerInfoActivity.this, binding.nickTV.getText().toString());
                mBottomDG.setMsgCallback(new MDialog.interfaceEdit() {
                    @Override
                    public void Receive(String message) {
                        binding.nickTV.setText(message);
                        binding.nickTV.setTextColor(getResources().getColor(R.color.C_333333));
                    }
                });
            }
        });

        binding.fTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.fTV.setTextColor(getResources().getColor(R.color.C_FFFFFF));
                binding.fTV.setBackgroundResource(R.drawable.corners_left_9065f9);
                binding.mTV.setTextColor(getResources().getColor(R.color.C_898B90));
                binding.mTV.setBackgroundResource(R.drawable.corners_right_e8e9f0);
                sex = 2;
            }
        });

        binding.mTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.fTV.setTextColor(getResources().getColor(R.color.C_898B90));
                binding.fTV.setBackgroundResource(R.drawable.corners_left_e8e9f0);
                binding.mTV.setTextColor(getResources().getColor(R.color.C_FFFFFF));
                binding.mTV.setBackgroundResource(R.drawable.corners_right_46a5f9);
                sex = 1;
            }
        });

        binding.birthTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                String now = sdf.format(new Date());
                customDatePicker = new CustomDatePicker(PerInfoActivity.this, new CustomDatePicker.ResultHandler() {
                    @Override
                    public void handle(String time) {
                        binding.birthTV.setText(time.split(" ")[0]);
                    }
                }, "1900-01-01 00:00", now);
                customDatePicker.showSpecificTime(false);
                customDatePicker.setIsLoop(false);
                customDatePicker.show("1990-01-01 00:00");
            }
        });

        binding.heightTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHPicker.show();
            }
        });

        binding.weightTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWPicker.show();
            }
        });

        binding.nextStepTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(binding.nickTV.getText().toString()))
                    ToastUtils.showShort(PerInfoActivity.this, "请输入昵称");
                else if (TextUtils.isEmpty(binding.heightTV.getText().toString()))
                    ToastUtils.showShort(PerInfoActivity.this, "请输入身高");
                else if (TextUtils.isEmpty(binding.weightTV.getText().toString()))
                    ToastUtils.showShort(PerInfoActivity.this, "请输入体重");
                else
                    viewModel.updateInfo(avatar, binding.nickTV.getText().toString(), sex, binding.birthTV.getText().toString(), binding.heightTV.getText().toString(), binding.weightTV.getText().toString());
            }
        });

        binding.enterTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewModel.getUserInfo();
            }
        });

        setRx(AppConstans.INFO, new BaseConsumer<UserInfoRes>() {
            @Override
            protected void onStart() {
                DialogUtils.waitingDialog(PerInfoActivity.this);
            }

            @Override
            protected void onSuccess(UserInfoRes mLiveData) {
                DialogUtils.dismiss(PerInfoActivity.this);
                SPUtils.putString(AppConstans.USER_INFO, new Gson().toJson(mLiveData.getData(), UserInfoRes.DataBean.class));
                Intent i = new Intent(PerInfoActivity.this, BalanceActivity.class);
                startActivity(i);
                finish();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(PerInfoActivity.this, error.getMessage());
                DialogUtils.dismiss(PerInfoActivity.this);
            }
        });

        setRx(AppConstans.UPDATE, new BaseConsumer<FileRes>() {
            @Override
            protected void onStart() {
                DialogUtils.waitingDialog(PerInfoActivity.this);
            }

            @Override
            protected void onSuccess(FileRes mLiveData) {
                DialogUtils.dismiss(PerInfoActivity.this);
                Glide.with(getApplicationContext())
                        .load(Uri.parse(mLiveData.getData().getUrl()))
                        .apply(RequestOptions.circleCropTransform())
                        .into(binding.header);
                avatar = mLiveData.getData().getUrl();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(PerInfoActivity.this, error.getMessage());
                DialogUtils.dismiss(PerInfoActivity.this);
            }
        });

        setRx(AppConstans.UPDATEINFO, new BaseConsumer<EmptyRes>() {
            @Override
            protected void onStart() {
                DialogUtils.waitingDialog(PerInfoActivity.this);
            }

            @Override
            protected void onSuccess(EmptyRes mLiveData) {
                DialogUtils.dismiss(PerInfoActivity.this);
                Intent i = new Intent(PerInfoActivity.this, TargetActivity.class);
                startActivity(i);
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(PerInfoActivity.this, error.getMessage());
                DialogUtils.dismiss(PerInfoActivity.this);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_per_info;
    }

    @Override
    protected Class getViewModelClass() {
        return TargetViewModel.class;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String path = AppConstans.BASE_PATH + AppConstans.HEAD_PATH_S;
            switch (requestCode) {
                case CAMERA_WITH_DATA:
                    File f = ImageUtils.zoomImageFile(AppConstans.BASE_PATH + AppConstans.HEAD_PATH, path, 1080);
                    if (f != null)
                        viewModel.updateHead(f);
                    break;
                case PHOTO_PICKED_WITH_PATH:
                    final Uri uri = data.getData();
                    if (uri != null) {
                        File f0 = ImageUtils.zoomImageFile(ImageUtils.uri2path(this, uri), path, 1080);
                        if (f0 != null)
                            viewModel.updateHead(f0);
                    }
                    break;
            }
        }
    }
}
